package com.jlnk.androidfmc.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.divider.MaterialDivider;
import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.entity.SettingItem;

import java.util.ArrayList;
import java.util.List;

public class SettingAdapter extends RecyclerView.Adapter<SettingAdapter.ItemViewHolder> {

  private final onClickListener onClick;
  private List<SettingItem> items = new ArrayList<>();

  public interface onClickListener {

    void onClick(SettingItem item);
  }

  public SettingAdapter(onClickListener onClick) {
    this.onClick = onClick;
  }

  public static class ItemViewHolder extends RecyclerView.ViewHolder {

    private TextView title, actionDesc;
    private MaterialDivider divider;

    public ItemViewHolder(@NonNull View itemView) {
      super(itemView);
      title = itemView.findViewById(R.id.item_title);
      actionDesc = itemView.findViewById(R.id.item_action_desc);
      divider = itemView.findViewById(R.id.item_divider);
    }

  }

  @NonNull
  @Override
  public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ItemViewHolder(
        LayoutInflater.from(parent.getContext()).inflate(R.layout.item_setting, parent, false)
    );
  }

  @Override
  public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
    final SettingItem item = items.get(position);
    ItemViewHolder vItem = holder;
    vItem.title.setText(item.getTitle());
    if (item.getActionDesc() != null) {
      vItem.actionDesc.setText(item.getActionDesc());
    }
    if (position == items.size() - 1) {
      vItem.divider.setVisibility(View.GONE);
    }
    holder.itemView.setOnClickListener(v -> onClick.onClick(item));
  }

  @Override
  public int getItemCount() {
    return items.size();
  }

  public void insertItem(SettingItem item) {
    this.items.add(item);
    notifyItemInserted(getItemCount());
    if (getItemCount() > 1) {
      notifyItemChanged(getItemCount() - 2);
    }
  }

  public void insertAllItems(List<SettingItem> items) {
    this.items.addAll(items);
    notifyItemRangeInserted(getItemCount() - items.size(), items.size());
    if (getItemCount() > 1) {
      notifyItemChanged(getItemCount() - 2);
    }
  }
}